import React, { useState, useEffect } from 'react';
import styles from './index.less';
import {
  Select,
  Input,
  DatePicker,
  Button,
  Table,
  Space,
  message,
  Form,
  Modal,
  Spin,
} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import locale from 'antd/es/date-picker/locale/zh_CN';
import 'moment/locale/zh-cn';
import SaleForm from '@/components/saleForm/index';
import {
  IGoodsType,
  IColumns,
  IData,
  IProps,
  IResponse,
  IFormItem,
} from './type';
import moment from 'moment';
import {
  getServiceFormData,
  deleteServiceGoods,
  searchGoods,
  resetGoods,
} from '@/service/goods';
import { observer } from 'mobx-react';
import store from '@/store';

const Sub1: React.FC = observer((props: IProps) => {
  // 给 form 定义 ref
  const [form] = Form.useForm();
  // 初始selectKey
  const initialSelectKey = null;

  const [selectList, setSelectList] = useState<IGoodsType[]>([]);
  const [formData, setFormData] = useState<IData[]>([]);
  const [visible, setVisible] = useState<boolean>(false);
  const [selectKey, setSelectKey] = useState<number | null>(initialSelectKey);
  const { spinning, setSpinning, getGoodsType } = store;
  const { confirm } = Modal;

  // 修改
  const modifyGoods = (record: IData): void => {
    setVisible(true);
    setSelectKey(record.key!);
  };

  // 删除弹框
  const showConfirm = (key: number): void => {
    confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      cancelText: '取消',
      okText: '确定',
      onOk() {
        return new Promise(
          (
            resolve: <T>(value?: T) => void,
            reject: () => void
          ) => {
            deleteFinish(key, resolve, reject);
          },
        );
      },
      onCancel() {
        console.log('取消');
      },
    });
  };

  // 请求删除元素的接口
  const deleteFinish = (
    key: number,
    resolve: () => void,
    reject: () => void,
  ): void => {
    deleteServiceGoods({ key })
      .then(async (res: IResponse) => {
        if (res && res.code == 200) {
          await getFormData();
        } 
        resolve();
      })
      .catch(() => {
        reject();
      });
  };

  // 新增按钮
  const handleVisible = (): void => {
    setVisible(true);
    setSelectKey(null);
  };

  // 请求搜索接口
  const search = (): void => {
    setSpinning(true);
    form.validateFields().then((res: IFormItem) => {
      let timeArr: Array<number> = [];
      res.picker?.forEach((item: moment.Moment, i: number) => {
        timeArr.push(moment(item).valueOf());
      });
      searchGoods({
        goodsType: res.norms,
        goodsName: res.name,
        time: timeArr,
      })
        .then((response: IResponse) => {
          if (!response.data!.length) {
            message.warning('当前搜索条件不存在表格内容！请重新选择');
          }
          if (response && response.code == 200) {
            setFormData(response.data as IData[]);
          }
          setSpinning(false);
        })
    });
  };

  const onFinish = () => {};

  // 重置按钮操作
  const resetField = (): void => {
    setSpinning(true);
    form.resetFields();
    resetGoods()
      .then(async (res: IResponse) => {
        if (res && res.code == 200) {
          await getFormData();
        }
        setSpinning(false);
      })
  };

  // 请求表格数据
  const getFormData = async (): Promise<void> => {
    const res = await getServiceFormData();
    if (res && res.code == 200) {
      setFormData(res.data as IData[]);
    }
  };

  const serviceLoading = async (): Promise<void> => {
    setSpinning(true);
    
    // 请求商品种类接口
    await getGoodsType().then((res: IResponse | undefined) => {
      setSelectList(res!.data as IGoodsType[]);
    });

    // 请求表格数据
    await getFormData();

    setSpinning(false);
  };

  useEffect(() => {
    serviceLoading();
  }, []);

  const { Option } = Select;
  const { RangePicker } = DatePicker;
  const columns: IColumns[] = [
    {
      title: '商品编码',
      dataIndex: 'goodsCode',
      align: 'center',
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      align: 'center',
    },
    {
      title: '商品规格',
      dataIndex: 'norms',
      align: 'center',
    },
    {
      title: '商品类别',
      dataIndex: 'goodsType',
      align: 'center',
    },
    {
      title: '单价',
      dataIndex: 'unit',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'time',
      align: 'center',
      render: (text: number) => {
        let now = new Date(text);
        // let y = now.getFullYear();
        // let mm = now.getMonth() + 1;
        // let d = now.getDate();
        // let h = now.getHours();
        // let minute = now.getMinutes();
        // let s = now.getSeconds();
        // return `${y}-${mm}-${d} ${h}:${minute}:${s}`;
        return moment(now).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (text: IData, record: IData) => {
        //但是这里很奇怪，这里的text和record的值是一样的
        //当前key无法匹配到对应字段导致返回全部数据
        return (
          <Space size="middle">
            <a onClick={() => modifyGoods(record)}>修改</a>
            <a onClick={() => showConfirm(record.key!)}>删除</a>
          </Space>
        );
      },
    },
  ];

  return (
    <Spin tip="加载中" spinning={spinning} className={styles.spin}>
      <div className={styles.saleContainer}>
        <h3>商品管理</h3>
        <div className={styles.searchDiv}>
          <Form
            name="form"
            style={{ padding: '24px 0' }}
            layout="inline"
            onFinish={onFinish}
            form={form}
          >
            <Form.Item name="norms">
              <Select
                placeholder="请选择商品种类"
                style={{ width: 180, marginRight: 30 }}
              >
                {selectList.map((item: IGoodsType) => {
                  return (
                    <Option value={item.type} key={item.id}>
                      {item.type}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item name="name">
              <Input
                placeholder="请输入商品名称"
                style={{ width: 200, marginRight: 30 }}
              />
            </Form.Item>
            <Form.Item name="picker">
              <RangePicker style={{ marginRight: 30 }} locale={locale} />
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                onClick={search}
                style={{ marginRight: '30px' }}
              >
                搜索
              </Button>
              <Button onClick={resetField}>重置</Button>
            </Form.Item>
          </Form>
        </div>
        <Button
          type="primary"
          style={{ margin: '0 0 30px 0' }}
          onClick={handleVisible}
        >
          新增
        </Button>
        <SaleForm
          visible={visible}
          selectKey={selectKey}
          getFormData={getFormData}
          handleCancel={() => setVisible(false)}
        />
        <Table
          columns={columns}
          dataSource={formData}
          style={{ width: '100%' }}
        />
      </div>
    </Spin>
  );
});

export default Sub1;